import React from 'react';
import {
  View,
  TextInput,
  TouchableOpacity,
  Text,
  StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { COLORS } from '../styles/constants';

/**
 * SearchBar 通用搜索栏
 * - controlled: value/onChange
 * - onSubmit: 提交搜索
 * - showCancel: 是否显示取消按钮
 * - onCancel: 点击取消
 */
export default function SearchBar({
  value,
  onChange,
  placeholder = '搜索',
  onSubmit,
  showCancel = false,
  onCancel,
  autoFocus = false,
  editable = true,
  onPressIn,
  showIcon = true,
  clearable = false,
  onClear,
}) {
  return (
    <View style={styles.row}>
      <View style={styles.inputWrapper}>
        {showIcon && (
          <Icon name="search" size={18} color={COLORS.text.quaternary} style={styles.icon} />
        )}
        {!editable && onPressIn ? (
          <TouchableOpacity
            onPress={onPressIn}
            style={[styles.input, styles.fakeInput]}
            activeOpacity={0.8}
          >
            <Text style={styles.placeholder}>{value || placeholder}</Text>
          </TouchableOpacity>
        ) : (
          <TextInput
            value={value}
            onChangeText={onChange}
            placeholder={placeholder}
            placeholderTextColor={COLORS.text.placeholder}
            returnKeyType="search"
            autoFocus={autoFocus}
            editable={editable}
            onSubmitEditing={onSubmit}
            onPressIn={onPressIn}
            style={styles.input}
          />
        )}
        {clearable && !!value && (
          <TouchableOpacity onPress={onClear} style={styles.clearBtn}>
            <Icon name="close-circle" size={18} color={COLORS.text.quaternary} />
          </TouchableOpacity>
        )}
      </View>
      {showCancel && (
        <TouchableOpacity style={styles.cancelBtn} onPress={onCancel}>
          <Text style={styles.cancelText}>取消</Text>
        </TouchableOpacity>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  inputWrapper: {
    flex: 1,
    backgroundColor: COLORS.white,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: COLORS.border.medium,
    shadowColor: COLORS.shadow,
    shadowOpacity: 0.1,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 6,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 8,
  },
  input: {
    height: 44,
    paddingHorizontal: 8,
    color: COLORS.text.primary,
    flex: 1,
  },
  fakeInput: {
    justifyContent: 'center',
  },
  placeholder: {
    color: COLORS.text.placeholder,
  },
  icon: { marginRight: 6 },
  clearBtn: { paddingHorizontal: 4 },
  cancelBtn: {
    marginLeft: 8,
    height: 44,
    paddingHorizontal: 12,
    alignItems: 'center',
    justifyContent: 'center',
  },
  cancelText: {
    color: COLORS.primary,
    fontSize: 16,
  },
});
